package com.dckj.auto.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dckj.auto.common.interceptor.AuthorityAnnotation;
import com.dckj.auto.common.utils.*;
import com.dckj.auto.common.utils.qiniu.QiNiuUpLode;
import com.dckj.auto.controller.help.UserMenuHelp;
import com.dckj.auto.entity.AuthMenu;
import com.dckj.auto.entity.AuthRole;
import com.dckj.auto.entity.AuthUserRole;
import com.dckj.auto.entity.User;
import com.dckj.auto.service.AuthMenuService;
import com.dckj.auto.service.AuthRoleService;
import com.dckj.auto.service.AuthUserRoleService;
import com.dckj.auto.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author WangDong123
 * @since 2018-07-11
 */
@Controller
@RequestMapping("/user/")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    AuthUserRoleService userRoleService;
    @Autowired
    AuthRoleService roleService;
    @Autowired
    AuthMenuService menuService;

    @RequestMapping(value = "login.action")
    public String loginAction(){
        return "user/login";
    }

    @RequestMapping(value = "login")
    @ResponseBody
    public Object login(HttpSession httpSession, String loginPhone, String loginPwd){
        User user = userService.selectOne(new EntityWrapper<User>().eq("phone",loginPhone));
        if(user==null){
            return JsonUtils.error(false,"手机号码不正确");
        }
        if(!MD5Encrypt.MD5Encode(loginPwd).equals(user.getPwd())){
            return JsonUtils.error(false,"登录密码不正确");
        }
        String sessionId = httpSession.getId();
        // 生成token
        StringBuffer token = new StringBuffer(loginPhone);
        token.append(System.currentTimeMillis()).append(sessionId);

        String newToken = MD5Encrypt.MD5Encode(token.toString());
        httpSession.setMaxInactiveInterval(43200);//12小时
        httpSession.setAttribute(PublicCode.LOGIN_KEY_TOKEN, newToken);//把token放到session中
        httpSession.setAttribute(PublicCode.USER_NAME,user.getName());//把用户名放到session中
        httpSession.setAttribute(PublicCode.USER_ID, user.getId());//把用户Id放到session中
        httpSession.setAttribute(PublicCode.USER_TYPE, user.getType());//用户类型

        return  JsonUtils.success(user.getType().toString());
    }



    /**退出登录
     *
     * @since 1.0
     * @throws Exception
     * <br><b>作者： @author WangDong</b>
     * <br>创建时间：2018-02-22 上午10:19:40
     */
    @RequestMapping(value = "logOut")
    public void logOut(HttpServletRequest request , HttpServletResponse response) throws Exception {
        request.getSession().setAttribute(PublicCode.USER_ID, "");//把用户Id设置为null
        request.getRequestDispatcher("/user/login.action").forward(request,response);
    }


    @RequestMapping(value = "welcome", method = RequestMethod.GET)
    public String welcome(HttpServletRequest request){
        //查询菜单数量，为0 则双击头像可以编辑新增菜单权限
        int count = menuService.selectCount(new EntityWrapper<AuthMenu>());
        request.setAttribute("menuCount",count);
        return "user/index";
    }


    @RequestMapping(value = "welcome/jsp")
    public String welcome_super(HttpServletRequest request){
        return "user/welcome";
    }


    @RequestMapping(value = "userAuto", method = RequestMethod.GET)
    @ResponseBody
    public JSONArray userAuto(HttpServletRequest request){
       return UserMenuHelp.userAuthMenu(request,1);
    }


    @AuthorityAnnotation(authority = AuthCode.USER_PAGE)
    @RequestMapping(value = "page")
    public String userPage(){
        return "user/manager/user_list";
    }

    @RequestMapping(value = "list")
    @ResponseBody
    public JSONObject list(HttpServletRequest request){
        Page<User> page = PageUtils.getPage(request);
        //排除开发人员以及不显示自己
        Page<User> page1 = userService.selectPage(page, new EntityWrapper<User>().and("type != {0} and id != {1} ",0,SessionUtil.userId(request)));
        List<User> records = page1.getRecords();
        if(records.size()<=0){
            return JsonUtils.toPage(page1);
        }
        List<String> userIds = new ArrayList<>();
        for (User user : records){
            userIds.add(user.getId());
        }
        List<AuthUserRole> userRoles = userRoleService.selectList(new EntityWrapper<AuthUserRole>().in("user_id", userIds));

        List<String> roleIds = new ArrayList<>();
        for (AuthUserRole userRole :userRoles){
            String roleId = userRole.getRoleId();
            if(!roleIds.contains(roleId)){
                roleIds.add(roleId);
            }
        }
        List<AuthRole> roles = roleService.selectList(new EntityWrapper<AuthRole>().in("id", roleIds));
        for (AuthUserRole userRole :userRoles){
            String roleId = userRole.getRoleId();
            for (AuthRole role : roles){
                String id = role.getId();
                if(roleId.equals(id)){
                    userRole.setId(role.getName());
                    break;
                }
            }
        }
        for (User user : records){
            user.setExtend("无角色");
            String userId = user.getId();
            for (AuthUserRole userRole :userRoles){
                String userId1 = userRole.getUserId();
                if(userId.equals(userId1)){
                    user.setExtend(userRole.getId());
                    break;
                }
            }
        }
        return JsonUtils.toPage(page1);
    }



    /**
     * 去修改密码
     * @return  String
     */
    @RequestMapping(value = "to/update/pwd")
    public String toUpdatePwd(HttpServletRequest request){
        String userId = StringUtil.getUserId(request);
        request.setAttribute("userId",userId);
        return "user/manager/pwd";//去修改密码
    }

    /**
     * 去修改密码
     * @return  Object
     */
    @RequestMapping(value = "do/update/pwd")
    @ResponseBody
    public Object updatePwd(String userId,String pwd,String newPwd){
        User users = userService.selectById(userId);
        String userPwd = users.getPwd();
        if(!MD5Encrypt.MD5Encode(pwd).equals(userPwd)){
            return JsonUtils.error( false,"原密码输入错误！");
        }
        users.setPwd(MD5Encrypt.MD5Encode(newPwd));
        // users.setUserPhone(userPhone);
        boolean update = userService.updateById(users);
        if(update){
            return JsonUtils.success( "密码修改成功，请牢记新密码！");
        }
        return JsonUtils.error( true,"密码修改失败！");
    }


    /**
     * 去修改密码
     * @return  String
     */
    @RequestMapping(value = "info")
    public String info(HttpServletRequest request){
        String userId = StringUtil.getUserId(request);
        User user = userService.selectById(userId);
        JSONObject jsonUser = new JSONObject();
        jsonUser.put("name",user.getName());
        jsonUser.put("phone",user.getPhone());
        jsonUser.put("pic",user.getPic());
        jsonUser.put("role","无角色");
        AuthUserRole role = userRoleService.selectOne(new EntityWrapper<AuthUserRole>().eq("user_id", userId));
        if(role != null){
            AuthRole authRole = roleService.selectById(role.getRoleId());
            jsonUser.put("role",authRole.getName());
        }
        request.setAttribute("user",jsonUser);
        return "user/manager/info";//去修改密码
    }




    /**
     * 去修改头像
     * @return  String
     */
    @RequestMapping(value = "to/update/pic")
    public String toUpdatePic(HttpServletRequest request){
        String userId = StringUtil.getUserId(request);
        Object attribute = request.getSession().getAttribute(PublicCode.USER_PIC);
        request.setAttribute("userId",userId);
        request.setAttribute("pic",attribute);
        return "user/manager/pic";//去修改头像
    }

    /**
     * 去修改头像
     * @return  Object
     */
    @RequestMapping(value = "do/update/pic")
    @ResponseBody
    public Object updatePic(HttpServletRequest request, String userId,String pic,String oldPic){
        User users = userService.selectById(userId);
        users.setPic(pic);
        boolean update = userService.updateById(users);
        if(StringUtils.isNotEmpty(oldPic) && (!oldPic.equals(pic)) && update ){
            QiNiuUpLode.delete(oldPic);
        }
        if(update){
            request.getSession().setAttribute(PublicCode.USER_PIC,pic);
            return JsonUtils.success( "更换个人头像");
        }
        return JsonUtils.error( true,"更换个人头像");
    }

}

